#include <exception>
#include <stdexcept>
#include <tools.hpp>
#include <string_view>

void print_help_exit(){
    throw std::runtime_error("if you want help please add \"-h\"\n");
}

int main(const int argc,const char *argv[]){
    try{
        if(argc==1){
            print_help_exit();
        }

        std::string argv1(argv[1]);
        if(argc==2){
            if(argv1=="-h"){
                zt::print("help:\n","\tThis is a simple string replacer to replace characters of the same length.\n","\t<string> <character to be replaced> <character to replace>\n","\t\t-By Zengtudor\n");
                return 0;
            }else{
                print_help_exit();
            }
        }else if(argc==4){
            std::string_view be_replaced(argv[2]),to_replace(argv[3]);
            if(be_replaced.size()!=to_replace.size()){
                throw std::runtime_error("The length of last two characters are not same!\n");
            }
            for(auto i: zt::Range(argv1.size())){
                if(argv1[i]==be_replaced[0]){
                    for(auto j: zt::Range(be_replaced.size())){
                        if(argv1[i+j]!=be_replaced[j]){
                            goto out_of_match;
                        }
                    }
                    for(auto j:zt::Range(be_replaced.size())){
                        argv1[i+j]=to_replace[j];
                    }
                }
                out_of_match:;
            }   
        }else{
            print_help_exit();
        }

        zt::print(argv1,"\n");

    }catch(const std::exception &e){
        zt::eprint("Caught an error because:\n","\t",NAME_VALUE(e.what()),"\n");
        return -1;
    }catch(...){
        zt::eprint("Caught an unknown error,closing...\n");
        std::rethrow_exception(std::current_exception());
    }
}